package controllers;

import entities.Statement;
import controllers.util.JsfUtil;
import controllers.util.PaginationHelper;
import entities.Categories;
import entities.Merchants;
import java.io.IOException;
import java.util.logging.Level;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import session.StatementFacade;

import java.io.Serializable;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import org.apache.log4j.Logger;
import session.CategoriesFacade;
import session.MerchantsFacade;
import workers.MerchantsWorker;
import workers.MerchantsWorkerImpl;
import workers.StatementsWorker;
import workers.StatementsWorkerImpl;
import workers.statements.StatementLoader;
import workers.statements.StatementLoaderImpl;
import workers.statements.beans.CCStatementCSV;

@ManagedBean(name = "statementByStatementPeriodController")
@SessionScoped
//@Stateless
public class StatementByStatementPeriodController implements Serializable {

    Logger logger = Logger.getLogger(StatementByStatementPeriodController.class);
    private Statement current;
    private DataModel items = null;
    @EJB
    private StatementFacade ejbFacade;
    @EJB
    private MerchantsFacade ejbMerchantsFacade;
    @EJB
    private CategoriesFacade ejbCategoriesFacade;
    @EJB
    private MerchantsWorker merchantsWorker;
    @EJB
    private StatementsWorker statementsWorker;
    @EJB
    private StatementLoader statementLoader;
    @Resource
    private UserTransaction utx;
    //@PersistenceContext(unitName = "wtfcc00PU")
    //EntityManager entityManager;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    public StatementByStatementPeriodController() {
    }

    public Statement getSelected() {
        if (current == null) {
            current = new Statement();
            selectedItemIndex = -1;
        }
        return current;
    }

    private StatementFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(50) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    DataModel dm = null;
                    int[] range = new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()};
                    List<Statement> s = getFacade().findRange(range);
                    dm = new ListDataModel(s);
                    return dm;
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "/web/statement/List";
    }

    public String prepareListByMerchant() {
        FacesContext context = FacesContext.getCurrentInstance();
        Map requestMap = context.getExternalContext().getRequestParameterMap();
        String merchantId = (String) requestMap.get("merchantId");
        System.out.println("prepareListByMerchant - merchantId:" + merchantId);

        return "/web/statementByMerchant/ListByMerchant";
    }

    public String prepareView() {
        current = (Statement) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Statement();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("StatementCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Statement) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("StatementUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Statement) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("StatementDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Statement.class)
    public static class StatementControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            StatementByStatementPeriodController controller = (StatementByStatementPeriodController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "statementController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Statement) {
                Statement o = (Statement) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + StatementByStatementPeriodController.class.getName());
            }
        }
    }

    /* my additions */
    private MerchantsFacade getMerchantsFacade() {
        return ejbMerchantsFacade;
    }

    /**
     * Loads new data into application.
     * 
     * @return 
     */
    public String load() throws IOException, ParseException, Exception {
        logger.debug("load() statement");
        statementLoader.load(StatementLoaderImpl.getSampleData());
        for (CCStatementCSV item : statementLoader.getDataList()) {
            List<Statement> statementsForAnyExistingRecords = statementsWorker.lookupStatements(item);
            if (statementsForAnyExistingRecords.size() > 0) {
                StringBuilder sb = new StringBuilder();
                sb.append("Will not reload statement item as already exists:");
                sb.append(item);
                logger.warn(sb.toString());
            } else {
                Merchants merchant = (Merchants) merchantsWorker.lookupMerchant(Merchants.replaceProblemChars(item.getMerchant())); // qmm.getResultList().get(0);
                Categories theOneCategory = null;
                logger.debug("  Merchant text:" + item.getMerchant() + ", merchant bean:" + merchant);
                if (merchant == null) {
                    // Create new merchant the user will need to clean up
                    merchant = merchantsWorker.createNewMerchant(item.getMerchant());
                    logger.debug(new StringBuilder().append("  Created merchant from new statement item - ").append(item.getMerchant()).append(", with Id:").append(merchant == null ? -1 : merchant.getId()).toString());
                } else {
                    List<Categories> categoriesForMerchant = merchantsWorker.lookupCategoriesForMerchant(merchant);
                    if (categoriesForMerchant != null) {
                        if (categoriesForMerchant.size() >= 1) {
                            theOneCategory = categoriesForMerchant.get(0);
                        } else {
                            theOneCategory = null;    // leave the edit window to present a drop-down list to let the user choose the category
                        }
                    }
                    logger.debug("      Category:" + theOneCategory);
                }
                logger.debug("        Create Statment bean");
                Statement statement = new Statement(item, merchant, theOneCategory);
                getFacade().create(statement);
            }
        }

        return prepareList();
    }
    
    private List<Statement> lookupStatements(CCStatementCSV statementCSVItem) {
        return null;
    }
}
